package com.health.system.security.auth;

import com.alibaba.druid.util.StringUtils;
import com.health.system.common.utils.ServletRequestUtil;
import com.health.system.dto.AuthorizationResourceDTO;
import com.health.system.dto.AuthorizationRoleDTO;
import com.health.system.mapper.ResourceMapper;
import com.health.system.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Collections;
/**
 * <a href = "https://docs.spring.io/spring-security/reference/5.8/servlet/appendix/faq.html#appendix-faq-matching-url-fragments">代码参考官方网址</a>
 * 自定义权限数据源
 *
 */
@Component
public class BlogSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private ResourceService resourceService;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        HttpServletRequest request = ServletRequestUtil.getRequest();
        String uri = request.getRequestURI();
        String method = request.getMethod();

        for (AuthorizationResourceDTO authorizations : resourceService.getResourcesAndRoles()) {
            if (checkUriAndMethod(uri, method, authorizations)) {
                String[] roles = authorizations.getRoles().stream().map(AuthorizationRoleDTO::getName).toArray(String[]::new);
                return SecurityConfig.createList(roles);
            }
        }
        return Collections.emptyList();
    }

    private static boolean checkUriAndMethod(String url, String method, AuthorizationResourceDTO authorizations) {
        boolean matchUrl = ANT_PATH_MATCHER.match(authorizations.getUrl(), url);
        boolean matchMethod = StringUtils.equals(authorizations.getMethod(), method);
        return matchUrl && matchMethod;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return Collections.emptyList();
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}
